package com.loe.ktui.util

import android.graphics.Outline
import android.view.View
import android.view.ViewOutlineProvider
import kotlin.math.min

class KtCornerProvider(var corner: Int, var cornerDirect: String, view: View) : ViewOutlineProvider()
{
    var w = 0
    var h = 0

    init
    {
        view.addOnLayoutChangeListener()
        { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
            w = view.width
            h = view.height
            val l = when (cornerDirect)
            {
                "top", "bottom" -> if (w > h)
                {
                    min(w / 2f, h.toFloat())
                } else
                {
                    w / 2f
                }
                "right", "left" -> if (h > w)
                {
                    min(w.toFloat(), h / 2f)
                } else
                {
                    h / 2f
                }
                else -> min(w, h) / 2f
            }
            corner = min(corner.toFloat(), l).toInt()

            view.clipToOutline = true
        }
    }

    override fun getOutline(view: View, outline: Outline)
    {
        when (cornerDirect)
        {
            "top" -> outline.setRoundRect(0, 0, w, h + corner, corner.toFloat())
            "right" -> outline.setRoundRect(-corner, 0, w, h, corner.toFloat())
            "bottom" -> outline.setRoundRect(0, -corner, w, h, corner.toFloat())
            "left" -> outline.setRoundRect(0, 0, w + corner, h, corner.toFloat())
            else -> outline.setRoundRect(0, 0, w, h, corner.toFloat())
        }
    }
}